package com.sishu.service.impl;

import com.sishu.mapper.*;
import com.sishu.pojo.*;
import com.sishu.pojo.VO.QuestionlibraryVo;
import com.sishu.pojo.VO.RoleVo;
import com.sishu.pojo.dto.TransactionRecorddto;
import com.sishu.service.TransactionRecordService;
import com.sishu.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ThreadLocalRandom;

@SuppressWarnings("rawtypes")
@Slf4j
@Service
public class TransactionRecordServiceimpl implements TransactionRecordService {

    @Resource
    private GameMapper gameMapper; // 游戏表

    @Resource
    private GusMapper gusMapper;    //中间表

    @Resource
    private GamegroupsMapper gamegroupsMapper;   //小组表

    @Resource
    private QuestionlibraryMapper questionlibraryMapper;

    @Resource
    private AssetMapper assetMapper;            //资产表

    @Resource
    private TransactionrecordMapper transactionrecordMapper;     //交易记录表

    @Resource
    private LocationlibraryMapper locationlibraryMapper;     //地盘表

    @Resource
    private LocationrecordMapper locationrecordMapper;       //地盘记录表


    @Resource
    private RoleMapper roleMapper; //角色表

    @Resource
    private OptionsMapper optionsMapper; //选项表

    private Set<Integer> usedQuestionIds = Collections.synchronizedSet(new HashSet<>());

    @Override
    public Result transactionrecord(Transactionrecord transactionrecord) {
        //1.首先确认游戏是否结束?  active==0?
        //1.1 首先得到该小组对应的gameId
        Gamegroups gamegroups = gamegroupsMapper.selectbygroupId(transactionrecord.getGroupId());
        String gameId = gamegroups.getGameId();
        Game selectgame = gameMapper.selectgame(gameId);
        if (selectgame.getActive() == 0) {
            return new Result(500, "游戏已结束", false);
        }

        //1.2在确认交易双方是否破产

        //我方为甲方/主动方,所以不会有银行
        Integer selectisdelete = gusMapper.selectisdelete(transactionrecord.getPartyA(), transactionrecord.getGroupId());
        if (selectisdelete != null && selectisdelete == 1) {
            return new Result<>(202, "破产", false);
        }

        //对方 为被动方,有可能时bank  当selectisdelete2为null时,表示是银行
        Integer selectisdelete2 = gusMapper.selectisdelete(transactionrecord.getPartyB(), transactionrecord.getGroupId());
        if (selectisdelete2 != null && selectisdelete2 == 1) {
            return new Result<>(202, "破产", false);
        }


        //2.交易模块
        //2.1 房租/转账
        if (transactionrecord.getType().equals("1")) {

            if (transactionrecord.getPartyA().equals(transactionrecord.getPartyB())) {
                return new Result(202, "不能交易自己", false);
            }


            Gus gusB = gusMapper.selectroleId(transactionrecord.getPartyB(), transactionrecord.getGroupId());//对方账号 (为房东)


            //2.1.1当种类类型为收租的时候 进行收租操作
            if (transactionrecord.getTypeDescribe().equals("1")) {
                //2.1.1.1 获得角色房东的角色信息
                if (gusB.getRoleId() == 13 || gusB.getRoleId() == 14 || gusB.getRoleId() == 15) {
                    Role roleB = roleMapper.selectRoleByroleId(gusB.getRoleId());

                    //2.获得更改后的金额                                                     原来的金额比如说是1000
                    int moneyB = transactionrecord.getMoneyB() + roleB.getRolePrice(); //对方的账号的金额 =1100
                    int moneyA = transactionrecord.getMoneyA() - roleB.getRolePrice(); //我方的账号的金额 =900

                    //3.更改资产表

                    //付款的账号(甲方)
                    Asset assetA = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                    //收款的账号(乙方)
                    Asset assetB = assetMapper.selectbysId(transactionrecord.getPartyB(), transactionrecord.getGroupId());


                    //付款人资金减少(包括总资产和流动资产)
                    assetMapper.updateasset(assetA.getSId(), moneyA, assetA.getGroupId());
                    //收款人资金增加(包括总资产和流动资产)
                    assetMapper.updateasset(assetB.getSId(), moneyB, assetB.getGroupId());


                    transactionrecord.setCreateTime(LocalDateTime.now()); //设置时间
                    transactionrecord.setMoneyA(moneyA);  //设置为更改后的金额
                    transactionrecord.setMoneyB(moneyB);
                    transactionrecord.setTypeDescribe("房租");
                    transactionrecordMapper.insert(transactionrecord); //插入交易记录表

                    //4. 更新gus表 gusB角色  也就是房东的技能次数
                    int upgradeTime = gusB.getUpgradeTimes();
                    int upgradeTime2 = upgradeTime + 1;

                    gusMapper.setupgradetimes(upgradeTime2, gusB.getSId(), gusB.getGroupId());//技能次数已更新

                    Gus gus2 = gusMapper.selectroleId(assetB.getSId(), assetB.getGroupId());

                    if (gus2.getUpgradeTimes() == 10) {  //如果技能次数为10，则升级为资深角色
                        gusMapper.setroleId(15, gus2.getSId(), gus2.getGroupId());
                        Role role2 = roleMapper.selectRoleByroleId(15);
                        //  return new Result(200, "data", "交易成功", role2, true);
                    }

                    if (gus2.getUpgradeTimes() == 5) {  //如果技能次数为5，则升级为高级角色
                        gusMapper.setroleId(14, gus2.getSId(), gus2.getGroupId());
                        Role role1 = roleMapper.selectRoleByroleId(14);
                        //   return new Result(200, "data", "交易成功", role1, true);
                    }

                    //查看数据更新后的资产信息
                    Asset assetAC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                    Asset assetBC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());

                    //2.2 交易后检查资金状态,要是某一方流动资金<0就进入复活状态  ,确认partyA是否拥有足够的fluidAsset
                    if (assetAC.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账
                        //进入答题界面答很难的题,答出来就奖励1000复活  只能限一次
                        return revivequestion(assetA.getSId(), assetA.getGroupId());
                    }

                    if (assetBC.getFluidAsset() < 0) {    //乙方流动资金不足时,进入破产状态,无法转账
                        return revivequestion(assetB.getSId(), assetB.getGroupId());
                    }

                    return new Result(202, "交易成功", true);
                }
                //当不是房东时的操作
                else {
                    // 2.1.1.2 不是房东时
                    //付款的账号(甲方)
                    Asset assetA = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                    //收款的账号(乙方)
                    Asset assetB = assetMapper.selectbysId(transactionrecord.getPartyB(), transactionrecord.getGroupId());


                    //付款人资金减少(包括总资产和流动资产)
                    assetMapper.updateasset(assetA.getSId(), transactionrecord.getMoneyA(), assetA.getGroupId());
                    //收款人资金减少(包括总资产和流动资产)
                    assetMapper.updateasset(assetB.getSId(), transactionrecord.getMoneyB(), assetB.getGroupId());


                    transactionrecord.setCreateTime(LocalDateTime.now()); //设置时间
                    transactionrecord.setTypeDescribe("房租");
                    transactionrecordMapper.insert(transactionrecord); //插入交易记录表


                    //查看数据更新后的资产信息
                    Asset assetAC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                    Asset assetBC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());

                    //2.1 确认partyA是否拥有足够的fluidAsset
                    if (assetAC.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账
                        //buyRecordMapper.saleallgrouds(groupid, payeruserId);
                        //进入答题界面答很难的题,答出来就奖励1000复活  只能限一次 功能未做
                        return revivequestion(assetA.getSId(), assetA.getGroupId());
                        // return new Result(202, "您已破产", true);
                    }

                    if (assetBC.getFluidAsset() < 0) {    //乙方流动资金不足时,进入破产状态,无法转账
                        //buyRecordMapper.saleallgrouds(groupid, payeruserId);
                        return revivequestion(assetB.getSId(), assetB.getGroupId());
                        // return new Result(202, "对方已破产", true);
                    }

                    return new Result(202, "交易成功", true);
                }
            } else {
                // 2.1.1.2 不是收租的操作
                //付款的账号(甲方)
                Asset assetA = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                //收款的账号(乙方)
                Asset assetB = assetMapper.selectbysId(transactionrecord.getPartyB(), transactionrecord.getGroupId());


                //付款人资金减少(包括总资产和流动资产)
                assetMapper.updateasset(assetA.getSId(), transactionrecord.getMoneyA(), assetA.getGroupId());
                //收款人资金减少(包括总资产和流动资产)
                assetMapper.updateasset(assetB.getSId(), transactionrecord.getMoneyB(), assetB.getGroupId());


                transactionrecord.setCreateTime(LocalDateTime.now()); //设置时间
                transactionrecord.setTypeDescribe("转账");
                transactionrecordMapper.insert(transactionrecord); //插入交易记录表

                //查看数据更新后的资产信息
                Asset assetAC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                Asset assetBC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());

                //2.1 确认partyA是否拥有足够的fluidAsset
                if (assetAC.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账
                    //buyRecordMapper.saleallgrouds(groupid, payeruserId);
                    //进入答题界面答很难的题,答出来就奖励1000复活  只能限一次 功能未做
                    return revivequestion(assetA.getSId(), assetA.getGroupId());
                    // return new Result(202, "您已破产", true);
                }

                if (assetBC.getFluidAsset() < 0) {    //乙方流动资金不足时,进入破产状态,无法转账
                    //buyRecordMapper.saleallgrouds(groupid, payeruserId);
                    return revivequestion(assetB.getSId(), assetB.getGroupId());
                    // return new Result(202, "对方已破产", true);
                }

                return new Result(202, "交易成功", true);
            }


        }
        //2.2 购买/抵押/改造   购买地盘(已完成)/出售地盘(已完成)
        if (transactionrecord.getType().equals("2")) {


            //付款的账号(甲方)      10003
            Asset assetA = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());

            //1.先查拥有的地盘信息 如果是自己的地盘，则进入升级地盘操作
            List<Locationrecord> locationrecordList = locationrecordMapper.selectbysidandgroupid(transactionrecord.getPartyA(), transactionrecord.getGroupId());


            //卖地
            if (transactionrecord.getMoneyA() > 0) { //卖地
                //1.通过地盘id查询地盘信息
                Locationlibrary location = locationlibraryMapper.selectbylocationid(transactionrecord.getLocationId());
                //2.通过地盘id和学生id查询地盘购买信息
                Locationrecord buyRecord = locationrecordMapper.selectbylocationIdandsid(assetA.getSId(), transactionrecord.getLocationId(), transactionrecord.getGroupId());
                if (buyRecord == null) {
                    return new Result(202, "用户没有此块地", false);
                }

                if (buyRecord.getUpgradeTimes() != 0) {
                    int money = (int) (buyRecord.getUpgradePrice() * 0.8);  //升级后的总价值*0.8

                    //5.更新资产表
                    assetMapper.saleground(assetA.getSId(), money, buyRecord.getUpgradePrice(), assetA.getGroupId());

                    //3.删除地盘购买信息
                    locationrecordMapper.deleteground(assetA.getSId(), transactionrecord.getLocationId(), transactionrecord.getGroupId());

                    //6. 插入交易记录表
                    transactionrecord.setCreateTime(LocalDateTime.now());
                    transactionrecord.setPartyB("bank");
                    //transactionrecord.setMoneyB(-location.getLocationPrice());
                    transactionrecord.setMoneyB(-money);
                    transactionrecord.setMoneyA(money);      //设置卖地收益为原来的0.8
                    transactionrecord.setTypeDescribe("抵押");
                    transactionrecordMapper.insert(transactionrecord);

                    //卖地操作不用检查流动资金不足的情况,因为这个是加流动资金
                    //查看数据更新后的资产信息
                    Asset assetAC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());

                    //卖地因为是给银行钱的,所以没有限制
//                    if (assetAC.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账
//
//                        return revivequestion(assetA.getSId(), assetA.getGroupId());
//                    }

                    return new Result(202, "交易成功", true);
                }

                //3.删除地盘购买信息
                locationrecordMapper.deleteground(assetA.getSId(), transactionrecord.getLocationId(), transactionrecord.getGroupId());

                //4.得到80%的收益
                int money = (int) (location.getLocationPrice() * 0.8);
                //5.更新资产表
                assetMapper.saleground(assetA.getSId(), money, location.getLocationPrice(), assetA.getGroupId());

                //6. 插入交易记录表
                transactionrecord.setCreateTime(LocalDateTime.now());
                transactionrecord.setPartyB("bank");
                transactionrecord.setMoneyB(-location.getLocationPrice());
                transactionrecord.setMoneyA(money);      //设置卖地收益为原来的0.8
                transactionrecord.setTypeDescribe("抵押");
                transactionrecordMapper.insert(transactionrecord);


                //查看数据更新后的资产信息
                Asset assetAC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                //卖地操作不用检查流动资金不足的情况,因为这个是加流动资金
                if (assetAC.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账

                    return revivequestion(assetA.getSId(), assetA.getGroupId());
                }

                return new Result(202, "交易成功", true);
            }


            boolean flag3 = false;//默认是没有相等的地盘的
            for (Locationrecord locationrecord : locationrecordList)
                if (locationrecord.getLocationId().equals(transactionrecord.getLocationId())) {

                    flag3 = true;
                    break;
                }

            //2.1.1 如果是自己的地盘，进入升级地盘操作
            if (flag3) {

                Gus gus = gusMapper.selectroleId(transactionrecord.getPartyA(), transactionrecord.getGroupId());

                if (gus == null) {
                    // 如果 gus 为 null，返回错误信息或采取其他措施
                    return new Result(400, "未找到对应的角色信息", false);
                }

                //如果此时流动资金不足直接返回交易失败
                //Asset assetAC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                //卖地操作不用检查流动资金不足的情况,因为这个是加流动资金
                if (assetA.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账

                    //return revivequestion(assetA.getSId(), assetA.getGroupId());
                    return new Result(202, "交易失败", false);
                }


                //当角色为工程师时，进入升级地盘价格-100 200 400
                if (gus.getRoleId() == 7 || gus.getRoleId() == 8 || gus.getRoleId() == 9) {
                    Role role = roleMapper.selectRoleByroleId(gus.getRoleId()); //获取roleId对应的角色信息


                    //得到这个地盘信息
                    Locationrecord locationrecord = locationrecordMapper.selectbylocationIdandsid(transactionrecord.getPartyA(), transactionrecord.getLocationId(), transactionrecord.getGroupId());
                    Locationlibrary selectbylocationid = locationlibraryMapper.selectbylocationid(locationrecord.getLocationId());

                    int upgradeTimes = locationrecord.getUpgradeTimes();  //0  1
                    upgradeTimes++;//1           2
                    int upgradeTimes2 = upgradeTimes + 1;  //2          3
                    //得到地盘后的升级价格
                    int upgradePrice = (selectbylocationid.getLocationPrice() * upgradeTimes2);  //500 * 2 =1000  500*3 =1500

                    int updatemoney = selectbylocationid.getLocationPrice() + role.getRolePrice();  //更新后付出的钱


                    // 1.更新资产表  减这个地的价格
                    assetMapper.buyground2(assetA.getSId(), updatemoney, selectbylocationid.getLocationPrice(), assetA.getGroupId());


                    // 2.更新locationrecord表
                    locationrecordMapper.updateupgradetimesandprice(transactionrecord.getPartyA(), transactionrecord.getLocationId(), transactionrecord.getGroupId(), upgradeTimes, upgradePrice); //sid locationid groupid upgradeTimes upgradePrice

                    //3. 插入交易记录表
                    transactionrecord.setCreateTime(LocalDateTime.now());
                    transactionrecord.setMoneyA(-updatemoney);
                    transactionrecord.setPartyB("bank");
                    transactionrecord.setMoneyB(updatemoney);
                    transactionrecord.setTypeDescribe("改造");
                    transactionrecordMapper.insert(transactionrecord);

                    //4. 更新gus表角色表技能次数
                    int upgradeTime = gus.getUpgradeTimes();
                    int upgradeTime2 = upgradeTime + 1;

                    gusMapper.setupgradetimes(upgradeTime2, gus.getSId(), gus.getGroupId());//技能次数已更新


                    Gus gus2 = gusMapper.selectroleId(assetA.getSId(), assetA.getGroupId());

                    if (gus2.getUpgradeTimes() == 4) {  //如果技能次数为4，则升级为资深角色
                        gusMapper.setroleId(9, gus2.getSId(), gus2.getGroupId());
                        Role role2 = roleMapper.selectRoleByroleId(9);
                        //    return new Result(200, "data", "交易成功", role2, true);
                    }

                    if (gus2.getUpgradeTimes() == 2) {  //如果技能次数为2，则升级为高级角色
                        gusMapper.setroleId(8, gus2.getSId(), gus2.getGroupId());
                        Role role1 = roleMapper.selectRoleByroleId(8);
                        //    return new Result(200, "data", "交易成功", role1, true);
                    }


                    return new Result(202, "交易成功", true);


                }


                //除工程师以外的角色 或者没有角色
                //得到这个地盘信息   查这个人的地盘信息
                Locationrecord locationrecord = locationrecordMapper.selectbylocationIdandsid(transactionrecord.getPartyA(), transactionrecord.getLocationId(), transactionrecord.getGroupId());


                Locationlibrary selectbylocationid = locationlibraryMapper.selectbylocationid(locationrecord.getLocationId());


                int upgradeTimes = locationrecord.getUpgradeTimes();  //0
                upgradeTimes++;//1
                int upgradeTimes2 = upgradeTimes + 1;  //2
                //得到地盘升级价格
                int upgradePrice = selectbylocationid.getLocationPrice() * upgradeTimes2;  //2*


                // 1.更新资产表  减这个地的价格
                assetMapper.buyground(assetA.getSId(), selectbylocationid.getLocationPrice(), assetA.getGroupId());

                // 2.更新locationrecord表
                locationrecordMapper.updateupgradetimesandprice(transactionrecord.getPartyA(), transactionrecord.getLocationId(), transactionrecord.getGroupId(), upgradeTimes, upgradePrice); //sid locationid groupid upgradeTimes upgradePrice

                //3. 插入交易记录表
                transactionrecord.setCreateTime(LocalDateTime.now());
                transactionrecord.setPartyB("bank");
                transactionrecord.setMoneyB(selectbylocationid.getLocationPrice());
                transactionrecord.setMoneyA(-selectbylocationid.getLocationPrice());
                transactionrecord.setTypeDescribe("改造");
                transactionrecordMapper.insert(transactionrecord);

                //查看数据更新后的资产信息
                Asset assetAC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                if (assetAC.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账
                    //buyRecordMapper.saleallgrouds(groupid, payeruserId);
                    //进入答题界面答很难的题,答出来就奖励1000复活  只能限一次 功能未做
                    return revivequestion(assetA.getSId(), assetA.getGroupId());
                    // return new Result(202, "您已破产", true);
                }

                return new Result(202, "交易成功", true);

            }

            if (transactionrecord.getMoneyA() < 0) { //买地

                Gus gus = gusMapper.selectroleId(transactionrecord.getPartyA(), transactionrecord.getGroupId());

                //卖地操作不用检查流动资金不足的情况,因为这个是加流动资金
                if (assetA.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账

                    //return revivequestion(assetA.getSId(), assetA.getGroupId());
                    return new Result(202, "交易失败", false);
                }

                //证明是销售,那么他的买地价格会便宜100
                if (gus.getRoleId() == 1 || gus.getRoleId() == 2 || gus.getRoleId() == 3) {

                    Role role = roleMapper.selectRoleByroleId(gus.getRoleId()); //获取roleId对应的角色信息


                    //通过地盘id查询地盘信息
                    Locationlibrary location = locationlibraryMapper.selectbylocationid(transactionrecord.getLocationId());


                    //查询该地盘是否被购买
                    List<Locationrecord> buyRecord = locationrecordMapper.selectbylocationid(location.getLocationId());

                    // 检查同组内是否有已购买的地盘
                    boolean flag = false;//默认没有

                    for (Locationrecord record : buyRecord) {
                        // 同一组的就不能买
                        if (record.getGroupId().equals(assetA.getGroupId())) {
                            flag = true;
                            break;
                        }
                    }
                    //如果有已购买地盘返回error
                    if (flag) {
                        return new Result(202, "同一组内地盘已经被购买", true);
                    }
                    //创建一个locationrecord对象
                    Locationrecord locationrecord = new Locationrecord();
                    locationrecord.setSId(transactionrecord.getPartyA());
                    locationrecord.setGroupId(transactionrecord.getGroupId());
                    locationrecord.setLocationId(transactionrecord.getLocationId());
                    locationrecord.setUpgradeTimes(0);
                    locationrecord.setUpgradePrice(location.getLocationPrice());


                    int updatemoney = location.getLocationPrice() + role.getRolePrice(); //比如 500 + (-100)
                    log.info("销售更新资金为" + updatemoney);


                    // 1.更新资产表
                    assetMapper.buyground2(assetA.getSId(), updatemoney, location.getLocationPrice(), assetA.getGroupId());

                    // 2.插入locationrecord表

                    locationrecordMapper.insert(locationrecord);

                    //3. 插入交易记录表
                    transactionrecord.setCreateTime(LocalDateTime.now());
                    transactionrecord.setMoneyA(-updatemoney);  //比如说500的地, 更新完后是400 ,那交易记录就是-400
                    transactionrecord.setPartyB("bank");
                    transactionrecord.setMoneyB(updatemoney);
                    transactionrecord.setTypeDescribe("购买");
                    transactionrecordMapper.insert(transactionrecord);

                    //4. 更新gus表角色表技能次数
                    int upgradeTime = gus.getUpgradeTimes();
                    int upgradeTime2 = upgradeTime + 1;

                    gusMapper.setupgradetimes(upgradeTime2, gus.getSId(), gus.getGroupId());//技能次数已更新


                    Gus gus2 = gusMapper.selectroleId(assetA.getSId(), assetA.getGroupId());

                    if (gus2.getUpgradeTimes() == 4) {  //如果技能次数为4，则升级为资深角色
                        gusMapper.setroleId(3, gus2.getSId(), gus2.getGroupId());
                        Role role2 = roleMapper.selectRoleByroleId(3);
                        // return new Result(200, "data", "交易成功", role2, true);
                    }

                    if (gus2.getUpgradeTimes() == 2) {  //如果技能次数为2，则升级为高级角色
                        gusMapper.setroleId(2, gus2.getSId(), gus2.getGroupId());
                        Role role1 = roleMapper.selectRoleByroleId(2);
                        //   return new Result(200, "data", "交易成功", role1, true);
                    }

                    return new Result(202, "交易成功", true);

                }

                //除销售以外的角色 或者没有角色


                //通过地盘id查询地盘信息
                Locationlibrary location = locationlibraryMapper.selectbylocationid(transactionrecord.getLocationId());

                log.info("location = " + location);

                //查询该地盘是否被购买
                List<Locationrecord> buyRecord = locationrecordMapper.selectbylocationid(location.getLocationId());

                // 检查同组内是否有已购买的地盘
                boolean flag = false;//默认没有

                for (Locationrecord record : buyRecord) {
                    // 同一组的就不能买
                    if (record.getGroupId().equals(assetA.getGroupId())) {
                        flag = true;
                        break;
                    }
                }
                //如果有已购买地盘返回error
                if (flag) {
                    return new Result(202, "同一组内地盘已经被购买", true);
                }
                //创建一个locationrecord对象
                Locationrecord locationrecord = new Locationrecord();
                locationrecord.setSId(transactionrecord.getPartyA());
                locationrecord.setGroupId(transactionrecord.getGroupId());
                locationrecord.setLocationId(transactionrecord.getLocationId());


                log.info("localtion.getlocationprice = " + location.getLocationPrice());

                // 1.更新资产表
                assetMapper.buyground(assetA.getSId(), location.getLocationPrice(), assetA.getGroupId());

                // 2.插入locationrecord表
                locationrecordMapper.insert(locationrecord);

                //3. 插入交易记录表
                transactionrecord.setCreateTime(LocalDateTime.now());
                transactionrecord.setPartyB("bank");
                transactionrecord.setMoneyB(location.getLocationPrice());
                transactionrecord.setMoneyA(-location.getLocationPrice());
                transactionrecord.setTypeDescribe("购买");
                transactionrecordMapper.insert(transactionrecord);

                //查看数据更新后的资产信息
                Asset assetAC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                if (assetAC.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账
                    //buyRecordMapper.saleallgrouds(groupid, payeruserId);
                    //进入答题界面答很难的题,答出来就奖励1000复活  只能限一次 功能未做
                    return revivequestion(assetA.getSId(), assetA.getGroupId());
                    //return new Result(202, "您已破产", true);
                }

                return new Result(202, "交易成功", true);

            }


        }
        //2.3 答题
        if (transactionrecord.getType().equals("3")) {


            //1.获取甲方的资产信息
            Asset assetA = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
            //2.获取甲方的gus角色
            Gus gus = gusMapper.selectroleId(transactionrecord.getPartyA(), transactionrecord.getGroupId());

            //3.1如果自己的角色为学者
            if (gus.getRoleId() == 10 || gus.getRoleId() == 11 || gus.getRoleId() == 12) {

                //3.1.1 获取roleId对应的角色信息
                Role role = roleMapper.selectRoleByroleId(gus.getRoleId());


                int updatemoney = transactionrecord.getMoneyA() + role.getRolePrice();  //更新后的钱 比如要-1000 +100 =-900

                assetMapper.updateasset(assetA.getSId(), updatemoney, assetA.getGroupId());

                //插入交易记录表
                transactionrecord.setCreateTime(LocalDateTime.now());
                transactionrecord.setPartyB("bank");
                transactionrecord.setMoneyB(-updatemoney);
                transactionrecord.setMoneyA(updatemoney);
                transactionrecord.setTypeDescribe("答题");
                transactionrecordMapper.insert(transactionrecord);

                //4. 更新gus表角色表技能次数
                int upgradeTime = gus.getUpgradeTimes();
                int upgradeTime2 = upgradeTime + 1;

                gusMapper.setupgradetimes(upgradeTime2, gus.getSId(), gus.getGroupId());//技能次数已更新

                Gus gus2 = gusMapper.selectroleId(assetA.getSId(), assetA.getGroupId());

                if (gus2.getUpgradeTimes() == 8) {  //如果技能次数为8，则升级为资深角色
                    gusMapper.setroleId(12, gus2.getSId(), gus2.getGroupId());
                    Role role2 = roleMapper.selectRoleByroleId(12);
                    //  return new Result(200, "data", "交易成功", role2, true);
                }

                if (gus2.getUpgradeTimes() == 4) {  //如果技能次数为4，则升级为高级角色
                    gusMapper.setroleId(11, gus2.getSId(), gus2.getGroupId());
                    Role role1 = roleMapper.selectRoleByroleId(11);
                    // return new Result(200, "data", "交易成功", role1, true);
                }


                //查看数据更新后的资产信息
                Asset assetAC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                if (assetAC.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账
                    //buyRecordMapper.saleallgrouds(groupid, payeruserId);
                    //进入答题界面答很难的题,答出来就奖励1000复活  只能限一次 功能未做
                    return revivequestion(assetA.getSId(), assetA.getGroupId());
                    //   return new Result(202, "您已破产", true);
                }


                return new Result(202, "交易成功", true);

            }


            //常规流程 没有角色或者角色不是学者
            //甲方的资产


            assetMapper.updateasset(assetA.getSId(), transactionrecord.getMoneyA(), assetA.getGroupId());

            //插入交易记录表
            transactionrecord.setCreateTime(LocalDateTime.now());
            transactionrecord.setPartyB("bank");
            transactionrecord.setMoneyB(-transactionrecord.getMoneyA());
            transactionrecord.setTypeDescribe("答题");
            transactionrecordMapper.insert(transactionrecord);


            //查看数据更新后的资产信息
            Asset assetAC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
            if (assetAC.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账
                //buyRecordMapper.saleallgrouds(groupid, payeruserId);
                //进入答题界面答很难的题,答出来就奖励1000复活  只能限一次 功能未做
                return revivequestion(assetA.getSId(), assetA.getGroupId());
                // return new Result(202, "您已破产", true);
            }


            return new Result(202, "交易成功", true);
        }

        //2.4 抽卡
        if (transactionrecord.getType().equals("4")) {

            //甲方的资产
            Asset assetA = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());

            //2.获取甲方的gus角色
            Gus gus = gusMapper.selectroleId(transactionrecord.getPartyA(), transactionrecord.getGroupId());

            //角色为会计
            if (gus.getRoleId() == 4 || gus.getRoleId() == 5 || gus.getRoleId() == 6) {

                //3.1.1 获取roleId对应的角色信息
                Role role = roleMapper.selectRoleByroleId(gus.getRoleId());


                int updatemoney = transactionrecord.getMoneyA() + role.getRolePrice();  //更新后的钱 比如要-1000 +100 =-900

                assetMapper.updateasset(assetA.getSId(), updatemoney, assetA.getGroupId());

                //插入交易记录表
                transactionrecord.setCreateTime(LocalDateTime.now());
                transactionrecord.setPartyB("bank");
                transactionrecord.setMoneyB(-updatemoney);
                transactionrecord.setMoneyA(updatemoney);
                transactionrecord.setTypeDescribe("抽卡");
                transactionrecordMapper.insert(transactionrecord);

                //4. 更新gus表角色表技能次数
                int upgradeTime = gus.getUpgradeTimes();
                int upgradeTime2 = upgradeTime + 1;

                gusMapper.setupgradetimes(upgradeTime2, gus.getSId(), gus.getGroupId());//技能次数已更新

                Gus gus2 = gusMapper.selectroleId(assetA.getSId(), assetA.getGroupId());

                if (gus2.getUpgradeTimes() == 8) {  //如果技能次数为8，则升级为资深角色
                    gusMapper.setroleId(6, gus2.getSId(), gus2.getGroupId());
                    Role role2 = roleMapper.selectRoleByroleId(6);
                    //  return new Result(200, "data", "交易成功", role2, true);
                }

                if (gus2.getUpgradeTimes() == 4) {  //如果技能次数为4，则升级为高级角色
                    gusMapper.setroleId(5, gus2.getSId(), gus2.getGroupId());
                    Role role1 = roleMapper.selectRoleByroleId(5);
                    //  return new Result(200, "data", "交易成功", role1, true);
                }

                //查看数据更新后的资产信息
                Asset assetAC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                if (assetAC.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账
                    //buyRecordMapper.saleallgrouds(groupid, payeruserId);
                    //进入答题界面答很难的题,答出来就奖励1000复活  只能限一次 功能未做
                    return revivequestion(assetA.getSId(), assetA.getGroupId());
                    //return new Result(202, "您已破产", true);
                }
                return new Result(202, "交易成功", true);

            }


            //更新资产表
            assetMapper.updateasset(assetA.getSId(), transactionrecord.getMoneyA(), assetA.getGroupId());

            //插入交易记录表
            transactionrecord.setCreateTime(LocalDateTime.now());
            transactionrecord.setPartyB("bank");
            transactionrecord.setMoneyB(-transactionrecord.getMoneyA());
            transactionrecord.setTypeDescribe("抽卡");
            transactionrecordMapper.insert(transactionrecord);

            //查看数据更新后的资产信息
            Asset assetAC = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
            //当没有角色或者角色不是会计时正常流程
            if (assetAC.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账
                //buyRecordMapper.saleallgrouds(groupid, payeruserId);
                //进入答题界面答很难的题,答出来就奖励1000复活  只能限一次 功能未做
                return revivequestion(assetA.getSId(), assetA.getGroupId());
                // return new Result(202, "您已破产", true);
            }

            return new Result(202, "交易成功", true);

        }


        return new Result<>(500, "没有此类交易种类", true);
    }

    @Override
    public Result transactionteamrecord(Transactionrecord transactionrecord) {
        //1.首先确认游戏是否结束?  active==0?
        //1.1 首先得到gameId
        Gamegroups gamegroups = gamegroupsMapper.selectbygroupId(transactionrecord.getGroupId());
        String gameId = gamegroups.getGameId();
        Game selectgame = gameMapper.selectgame(gameId);
        if (selectgame.getActive() == 0) {
            return new Result(500, "游戏已结束", false);
        }

        //收租操作
        if (transactionrecord.getType().equals("1")) {

            //得到对方小组的gus信息
            List<Gus> gusB = gusMapper.selectteam(transactionrecord.getPartyB(), transactionrecord.getGroupId());

            if (transactionrecord.getTypeDescribe().equals("1")) {
                int countrole = 0;
                List<Gus> list = new ArrayList<>();
                //遍历gusB
                for (Gus gus : gusB) {

                    if (gus.getRoleId() == 13 || gus.getRoleId() == 14 || gus.getRoleId() == 15) {
                        countrole++;
                        list.add(gus);

                    }
                }


                //证明对面有一个房东,就按照一个的价格走
                if (countrole == 1) {
                    //得到该房东的角色信息
                    Role roleB = roleMapper.selectRoleByroleId(list.get(0).getRoleId());
                    //2.获得更改后的金额                                                     原来的金额比如说是1000
                    int moneyB = transactionrecord.getMoneyB() + roleB.getRolePrice(); //t2  对方的账号的金额 =1100
                    int moneyA = transactionrecord.getMoneyA() - roleB.getRolePrice(); //t1 我方的账号的金额 =900

                    //3.更改资产表
                    //付款的账号(甲方)  t1
                    Asset assetA = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                    //收款的账号(乙方)  t2
                    Asset assetB = assetMapper.selectbysId(transactionrecord.getPartyB(), transactionrecord.getGroupId());

                    Result checkassetA = checkasset(assetA);
                    if (!checkassetA.isSuccess()) return checkassetA;

                    Result checkassetB = checkasset(assetB);
                    if (!checkassetB.isSuccess()) return new Result(202, "对方已破产", false);

                    Decreasedfunds(assetA, moneyA); //付款人资金减少(包括总资产和流动资产)
                    Decreasedfunds(assetB, moneyB); //收款人资金减少(包括总资产和流动资产)

                    inserttransactionrecord(transactionrecord, moneyA, moneyB); //插入交易记录表

                    Result updategusfangdong = updategusfangdong(list.get(0));  //更新gus表

                    return updategusfangdong;

                }
                //证明对面有两个房东,就按照两个的价格走
                if (countrole == 2) {
                    Role roleA = roleMapper.selectRoleByroleId(list.get(0).getRoleId()); //获取第一个房东的角色信息
                    Role roleB = roleMapper.selectRoleByroleId(list.get(1).getRoleId());  //获取第二个房东的角色信息

                    //2.获得更改后的金额                                                     原来的金额比如说是1000
                    int moneyB = transactionrecord.getMoneyB() + roleA.getRolePrice() + roleB.getRolePrice(); //t2  对方的账号的金额 =1100
                    int moneyA = transactionrecord.getMoneyA() - roleA.getRolePrice() - roleB.getRolePrice(); //t1 我方的账号的金额 =900


                    //3.更改资产表
                    //付款的账号(甲方)  t1
                    Asset assetA = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId());
                    //收款的账号(乙方)  t2
                    Asset assetB = assetMapper.selectbysId(transactionrecord.getPartyB(), transactionrecord.getGroupId());

                    Result checkassetA = checkasset(assetA);
                    if (!checkassetA.isSuccess()) return checkassetA;

                    Result checkassetB = checkasset(assetB);
                    if (!checkassetB.isSuccess()) return new Result(202, "对方已破产", false);

                    Decreasedfunds(assetA, moneyA); //付款人资金减少(包括总资产和流动资产)
                    Decreasedfunds(assetB, moneyB); //收款人资金减少(包括总资产和流动资产)

                    inserttransactionrecord(transactionrecord, moneyA, moneyB); //插入交易记录表

                    Result updategusfangdong = updategusfangdong(list.get(0));  //更新gus表 第一个房东
                    Result updategusfangdong2 = updategusfangdong(list.get(1));  //更新gus表 第二个房东

                    //判断是否都成功 , 都成功就返回一个list
                    List<RoleVo> list1 = new ArrayList<>();
                    if (updategusfangdong.getData() != null && updategusfangdong2.getData() != null) {
                        list1.add((RoleVo) updategusfangdong.getData());
                        list1.add((RoleVo) updategusfangdong2.getData());
                        return new Result(200, "data", "交易成功", list1, true);
                    }
                    if (updategusfangdong.getData() != null) {
                        return updategusfangdong;
                    }
                    if (updategusfangdong2.getData() != null) {
                        return updategusfangdong2;
                    }
                    return updategusfangdong;
                }
            }

            //不是收租操作 或者对面角色不是房东的情况下就正常交易
            //付款的账号(甲方)
            Asset assetA = assetMapper.selectbysId(transactionrecord.getPartyA(), transactionrecord.getGroupId()); //t1
            //收款的账号(乙方)
            Asset assetB = assetMapper.selectbysId(transactionrecord.getPartyB(), transactionrecord.getGroupId()); //t2
            //2.1 确认partyA是否拥有足够的fluidAsset
            Result checkassetA = checkasset(assetA);
            if (!checkassetA.isSuccess()) return checkassetA;

            Result checkassetB = checkasset(assetB);
            if (!checkassetB.isSuccess()) return checkassetB;
            //return new Result(202, "对方已破产", false);


            Decreasedfunds(assetA, transactionrecord.getMoneyA()); //付款人资金减少(包括总资产和流动资产)
            Decreasedfunds(assetB, transactionrecord.getMoneyB()); //收款人资金减少(包括总资产和流动资产)


            transactionrecord.setCreateTime(LocalDateTime.now()); //设置时间
            transactionrecordMapper.insert(transactionrecord); //插入交易记录表

            return new Result(202, "交易成功", true);
        }

        return null;
    }

    @Override
    public Result selectrecord(Transactionrecord record) {
//        if (record.getGroupId() == null || record.getGroupId().isEmpty()) {
//            return new Result<>(500, "请输入groupId", false);
//        }


        List<TransactionRecorddto> selectrecord = transactionrecordMapper.selectrecord(record);

        log.info("selectrecord = " + selectrecord);


        //当获取到的数据为空时,将获取到的数据中的geterUserName设置为bank(因为id为bank的在student表中没有对应名字)
        for (TransactionRecorddto transactionRecorddto : selectrecord) {
            if (transactionRecorddto.getGeterUserName() == null || transactionRecorddto.getGeterUserName().isEmpty()) {
                transactionRecorddto.setGeterUserName("bank");
            }
        }

        if (selectrecord == null) {
            return new Result<>(202, "没有交易记录", false);
        }

        return new Result<>(200, "list", selectrecord, "查询成功", true);
    }

//    @Override
//    public Result seerecordbygroupId(Transactionrecord record) {
//
//        //返回的是该组的信息
//       // List<TransactionRecordVO> selectrecord = transactionrecordMapper.seerecordbygroupId(record);
//
//        if (selectrecord == null) {
//            return new Result<>(202, "没有交易记录", false);
//        }
//
//        return new Result<>(200, "list", selectrecord, "查询成功", true);
//
//
//    }


    //检查资金  team模式用的

    public Result checkasset(Asset asset) {
        if (asset.getFluidAsset() < 0) {    //甲方流动资金不足时,进入破产状态,无法转账
            //buyRecordMapper.saleallgrouds(groupid, payeruserId);
            //进入答题界面答很难的题,答出来就奖励1000复活  只能限一次 功能未做
            return revivequestion(asset.getSId(), asset.getGroupId());
            // return new Result(202, "您已破产", false);
        }
        return new Result(202, "您还有足够的资金", true);
    }

    //减少总资金与流动资产
    public void Decreasedfunds(Asset asset, int money) {
        assetMapper.updateasset(asset.getSId(), money, asset.getGroupId());
    }

    //插入交易记录表
    public void inserttransactionrecord(Transactionrecord record, int moneyA, int moneyB) {
        record.setCreateTime(LocalDateTime.now()); //设置时间
        record.setMoneyA(moneyA);  //设置为更改后的金额
        record.setMoneyB(moneyB);
        transactionrecordMapper.insert(record); //插入交易记录表

    }

    //更新角色表-房东 team模式用的
    public Result updategusfangdong(Gus gus) {
        //4. 更新gus表 gus角色  也就是房东的技能次数
        int upgradeTime = gus.getUpgradeTimes();
        int upgradeTime2 = upgradeTime + 1;

        gusMapper.setupgradetimes(upgradeTime2, gus.getSId(), gus.getGroupId());//技能次数已更新

        Gus gus2 = gusMapper.selectroleId(gus.getSId(), gus.getGroupId());

        if (gus2.getUpgradeTimes() == 6) {  //如果技能次数为6，则升级为资深角色
            gusMapper.setroleId(15, gus2.getSId(), gus2.getGroupId());
            Role role2 = roleMapper.selectRoleByroleId(15);

            RoleVo roleVo = new RoleVo(gus2.getSId(), gus2.getGroupId(), role2.getRoleId(), role2.getRoleName(), role2.getSkillName(), role2.getLevel(), role2.getLevelName(), role2.getUpgradeCondition(), role2.getRolePrice());
            return new Result(200, "data", "交易成功,对方已晋升", roleVo, true);
        }

        if (gus2.getUpgradeTimes() == 3) {  //如果技能次数为3，则升级为高级角色
            gusMapper.setroleId(14, gus2.getSId(), gus2.getGroupId());
            Role role1 = roleMapper.selectRoleByroleId(14);
            RoleVo roleVo2 = new RoleVo(gus2.getSId(), gus2.getGroupId(), role1.getRoleId(), role1.getRoleName(), role1.getSkillName(), role1.getLevel(), role1.getLevelName(), role1.getUpgradeCondition(), role1.getRolePrice());

            return new Result(200, "data", "交易成功,对方已晋升", roleVo2, true);
        }
        return new Result(202, "交易成功", true);
    }

    //复活机制
    public Result revivequestion(String partyA, String groupId) {

        //1.先检查复活甲机制是不是1 如果是1就返回已经使用复活甲
        if (gusMapper.selectrevivefirstused(partyA, groupId) == 1) {
            return new Result(202, "破产", false);
        }
        //2.在题库抽取3个题目(巨难题目)交给前端
        List<QuestionlibraryVo> allTikus = questionlibraryMapper.selcetbyclasshour(999);

        System.out.println("allTikus=" + allTikus);


        List<QuestionlibraryVo> allTikus1 = new ArrayList<>();

        for (QuestionlibraryVo tikus : allTikus) {
            tikus.setPartyA(partyA);
            tikus.setGroupId(groupId);
            allTikus1.add(tikus);
        }

        log.info("allTikus1=" + allTikus1);


        if (CollectionUtils.isEmpty(allTikus1)) {//如果数据库中没有数据那么会返回题库为空
            return new Result<>(500, "题库为空", false);
        }

        List<QuestionlibraryVo> availableTikus = new ArrayList<>(); // 存储未被使用过的题目
        for (QuestionlibraryVo tiku : allTikus1) {
            if (!usedQuestionIds.contains(tiku.getQuestionId())) { // 遍历 allTikus 列表，检查每个题目的 questionId 是否在 usedQuestionIds 集合中
                availableTikus.add(tiku); // 如果 questionId 不在 usedQuestionIds 中，将该题目添加到 availableTikus 列表中
            }
        }

        List<QuestionlibraryVo> selectedTikus = new ArrayList<>();
        int numberOfQuestions = 3;

        // 如果可用题目数量不足，则允许重复使用之前的题目
        if (availableTikus.size() < numberOfQuestions) {
            // 允许重复使用之前的题目
            for (int i = 0; i < numberOfQuestions; i++) {
                int randomIndex = ThreadLocalRandom.current().nextInt(allTikus.size());
                QuestionlibraryVo selectedTiku = allTikus.get(randomIndex);

                List<Options> options = optionsMapper.selectOptionsByQuestionId(selectedTiku.getQuestionId());
                selectedTiku.setOptions(options);

                selectedTikus.add(selectedTiku);
            }
        } else {
            // 随机选择三个题目
            for (int i = 0; i < numberOfQuestions; i++) {
                int randomIndex = ThreadLocalRandom.current().nextInt(availableTikus.size());
                QuestionlibraryVo selectedTiku = availableTikus.remove(randomIndex); // 移除已选中的题目，避免重复选择
                List<Options> options = optionsMapper.selectOptionsByQuestionId(selectedTiku.getQuestionId());
                selectedTiku.setOptions(options);
                selectedTikus.add(selectedTiku);
                // 记录已使用的 questionId
                usedQuestionIds.add(selectedTiku.getQuestionId());
            }
        }

        //最后一步 设置复活甲为1(已使用)
        gusMapper.revivefirstusedone(partyA, groupId);

        return new Result<>(200, "list", selectedTikus, "复活随机题目获取成功", true);
    }

}
